const UserService = require('../service/user');
const WorkerService = require('../service/worker');
const OrganizationService = require('../service/organization');
const NoticeService = require('../service/notice');

const { logger, mergeAgent, cloudApiClient } = require('../utils');
const { v4 } = require('uuid');
const organizationService = new OrganizationService();

const userService = new UserService();
const workerService = new WorkerService();
const noticeService = new NoticeService();

module.exports = app => {
  // 员工列表
  app.post(`${process.env.VUE_APP_BASE_API}/staff/list`, async (req, res) => {
    const { body, userInfo, token } = req;
    const { Offset, Limit, Filters } = body;
    if (userInfo) {
      const params = {
        Agent: mergeAgent({
          ProxyOrganizationOpenId: userInfo.organizationOpenId,
          OpenId: userInfo.openId,
          ProxyAppId: userInfo.ProxyAppId,
        }),
        ...body,
      };
      try {
        const data = await cloudApiClient.ChannelDescribeEmployees(params);
        console.log('🚀 ~ file: user.js:30 ~ app.post ~ data', data);

        // 同步到本地数据库
        const employees = data.Employees;
        const where = {
          organizationId: userInfo.organizationId,
        };
        if (Filters) {
          Filters.forEach(f => {
            const val = f.Values[0];
            if (val === 'IsVerified') {
              where.verified = true;
            } else if (val === 'QuiteJob') {
              where.quiteJob = 1;
            }
          });
        }

        await userService.batchSyncUserList(employees, userInfo.organizationOpenId);
        const listData = await userService.list(where, Offset, Limit);
        const totalCount = await userService.count(where);
        res.json({
          code: 20000,
          data: {
            list: listData,
            totalCount,
          },
        });
      } catch (err) {
        console.error(err, 'ChannelDescribeEmployees Error===');
        logger.error({
          ...params,
          Action: 'ChannelDescribeEmployees',
          message: err.message,
          stack: err.stack,
        });
        res.json({
          code: 50000,
          message: err.message,
        });
      }
    } else {
      logger.error({
        Action: 'staff/list',
        token,
        message: '用户信息不存在',
      });
      res.json({
        code: 500,
        message: '用户信息不存在',
      });
    }
  });
  // 经办人同步
  app.post(`${process.env.VUE_APP_BASE_API}/staff/update`, async (req, res) => {
    const { body, userInfo, token } = req;
    if (userInfo) {
      if (body.OperatorType !== 'RESIGN') {
        body.ProxyOrganizationOperators = body.ProxyOrganizationOperators.map(v => {
          const paramsTemp = {
            Name: v.userName,
            Mobile: v.mobile,
            // IdCardType: v.idCardType,
            // IdCardNumber: v.idCardNumber,
          };
          if (body.OperatorType === 'CREATE') {
            return {
              Id: v4().replace(/-/, ''),
              ...paramsTemp,
            };
          }
          return { Id: v.openId, ...paramsTemp };
        });
      }
      // 直接走列表更新同步
      // await userService.createOrUpdate({
      //   ...body,
      //   organizationId: userInfo.organizationId,
      // });
      const params = {
        Agent: mergeAgent({
          ProxyOrganizationOpenId: userInfo.organizationOpenId,
          OpenId: userInfo.openId,
        }),
        ...body,
      };

      cloudApiClient.SyncProxyOrganizationOperators(params).then(
        data => {
          if (data.Status === 1) {
            // 同步到本地数据库

            res.json({
              code: 20000,
              data,
            });
          } else {
            res.json({
              code: 50000,
              message: data.FailedList?.[0]?.Message,
            });
          }
        },
        err => {
          logger.error({
            ...params,
            Action: 'SyncProxyOrganizationOperators',
            message: err.message,
            stack: err.stack,
          });
          res.json({
            code: 50000,
            message: err.message,
            stack: err.stack,
          });
        },
      );
    } else {
      logger.error({
        Action: 'staff/update',
        token,
        message: '用户信息不存在',
      });
      res.json({
        code: 50000,
        message: '用户信息不存在',
      });
    }
  });
  // 批量同步数据专用接口，登录成功调用,刷新列表时调用
  app.post(`${process.env.VUE_APP_BASE_API}/staff/sync`, async (req, res) => {
    const { userInfo } = req;
    if (userInfo) {
      const params = {
        Agent: mergeAgent({
          ProxyOrganizationOpenId: userInfo.organizationOpenId,
          OpenId: userInfo.openId,
        }),
        Limit: 0,
        Offset: 0,
      };
      try {
        const data = await cloudApiClient.ChannelDescribeEmployees(params);
        const employees = data.Employees;
        await userService.batchSyncUserList(employees, userInfo.organizationOpenId);
        res.json({
          code: 20000,
          data,
        });
      } catch (err) {
        console.error(err, 'ChannelDescribeEmployees===');
        logger.error({
          ...params,
          Action: 'ChannelDescribeEmployees',
          message: err.message,
          stack: err.stack,
        });
        res.json({ code: 50000, message: err.message });
      }
      return;
    }
    res.json({ code: 401, message: '登录失败，用户不存在' });
  });

  app.post(`${process.env.VUE_APP_BASE_API}/user/logout`, async (req, res) => {
    res.json({
      code: 20000,
    });
  });
  app.post(`${process.env.VUE_APP_BASE_API}/user/login`, async (req, res) => {
    const { body = {} } = req;
    const { mobile } = body;

    const result = await userService.first({ mobile });
    if (result) {
      const targetUser = result;
      res.json({
        code: 20000,
        data: { token: targetUser.userId },
      });
      return;
    }
    logger.error('登录失败, 用户不存在');
    res.json({
      code: 50204,
      message: '登录失败, 用户不存在',
    });
  });

  app.post(`${process.env.VUE_APP_M_BASE_API}/user/mLogin`, async (req, res) => {
    const { body = {} } = req;
    const { mobile } = body;
    const workerData = await workerService.first({ mobile });
    if (workerData) {
      res.json({
        code: 20000,
        data: { token: workerData.id }, // TODO
      });
      return;
    }
    logger.error('登录失败, 用户不存在');
    res.json({
      code: 50204,
      message: '登录失败, 用户不存在',
    });
  });

  app.post(`${process.env.VUE_APP_M_BASE_API}/user/getWorkerOrganizations`, async (req, res) => {
    const { userInfo } = req;
    const result = [];
    const hash = {};
    const workerData = await workerService.filter({ mobile: userInfo.mobile });
    await Promise.all(workerData.map(v => organizationService.find(v.organizationId).then(data => {
      if (data && !hash[data.id]) {
        hash[data.id] = true;
        result.push({ ...data, workerId: v.id });
      }
    })));

    if (workerData) {
      res.json({
        code: 20000,
        data: { organizations: result, totalCount: result.length },
      });
      return;
    }
    logger.error('查询机构失败');
    res.json({
      code: 50204,
      message: '登录失败, 用户不存在',
    });
  });
  app.post(`${process.env.VUE_APP_M_BASE_API}/user/logout`, async (req, res) => {
    res.json({
      code: 20000,
    });
  });

  async function getUserInfo(req, res) {
    const { userInfo } = req;
    const targetUser = userInfo;
    if (userInfo?.organizationId) {
      const orgData = await organizationService.find(userInfo.organizationId);
      res.json({ data: { ...targetUser, organizationName: orgData?.organizationName }, code: 20000 });
      return;
    }
    res.json({
      code: 50204,
      message: '用户不存在',
    });
  }

  app.get(`${process.env.VUE_APP_BASE_API}/user/info`, getUserInfo);
  app.get(`${process.env.VUE_APP_M_BASE_API}/user/info`, getUserInfo);

  // 同步json数据到redis中
  app.get(`${process.env.VUE_APP_BASE_API}/user/sync`, async (req, res) => {
    try {
      await userService.syncJson();
      res.status(200).json({
        message: 'ok',
      });
    } catch (err) {
      res.status(500).json({
        code: 500,
        stack: err.stack,
        message: err.message,
      });
    }
  });

  // 查询全量users数据
  app.get(`${process.env.VUE_APP_BASE_API}/user/list`, async (req, res) => {
    try {
      const userList = await userService.list();
      res.status(200).json({
        data: userList,
      });
    } catch (err) {
      res.status(500).json({
        code: 500,
        stack: err.stack,
        message: err.message,
      });
    }
  });

  // 员工实名认证
  app.post(`${process.env.VUE_APP_BASE_API}/staff/verify`, async (req, res) => {
    const { body, userInfo } = req;
    const { user } = body;

    let params = {};
    if (userInfo?.organizationId && userInfo.userId) {
      params = {
        Agent: mergeAgent({
          ProxyOrganizationOpenId: userInfo.organizationId,
          OpenId: user.userId || user.openId,
        }),
        ProxyOrganizationName: userInfo.organizationName,
        ProxyOperatorName: user.userName,
        Endpoint: 'PC',
        MenuStatus: 'ENABLE',
      };
    }

    cloudApiClient.CreateConsoleLoginUrl(params).then(
      data => {
        if (data.ConsoleUrl) {
          return res.json({
            code: 20000,
            data,
          });
        }
        return res.json(data);
      },
      err => {
        logger.error({
          ...params,
          Action: 'CreateConsoleLoginUrl',
          message: err,
        });
        res.json({
          code: 500,
          err,
        });
      },
    );
  });

  // 员工列表
  app.get(`${process.env.VUE_APP_BASE_API}/notice/list`, async (req, res) => {
    const { userInfo } = req;
    const data = await noticeService.filter({
      organizationId: userInfo.organizationId,
    }, 0, 8);
    res.json({
      code: 20000,
      data,
    });
  });
};
